package com.guokai2012.util;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;


/**
 * @Author: guokai
 * @Date: 2021/7/24 21:15
 * @Description: 主面板设计，启用。改 JTable使用
 */
public class MainJPanel {
    private JFrame frame;
    private JPanel jpl;
    private JScrollPane jsp;
    private List<JPanel> panelList = new ArrayList<>();

    public MainJPanel(JFrame frame) {
        this.frame = frame;
    }

    public void init() {
        // 先布局 底层 滚动加面板
        this.jpl = new JPanel();
        // 设置 box布局，并设置Y轴方向布局
        jpl.setLayout(new BoxLayout(jpl, BoxLayout.Y_AXIS));

        // 主面板设置滚动
        jsp = new JScrollPane(jpl);

        // 面板添加鼠标点击事件
        jpl.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                // 当鼠标点击时，自动创建一个 输入框，方便新建任务
                System.out.println("点击xx");
                addTextField();
                updateUI();
            }
        });

        jpl.setVisible(true);
        // 将主面板添加到frame上
        frame.add(jsp);
    }

    /**
     * 添加 任务输出框
     *
     * @return
     */
    private JPanel addTextField() {
        JPanel panel = new JPanel();
        // 设置布局
        panel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();

        // 设置 下边框成一条线，并拉大外边距，以便可以点击窗口
        panel.setBorder(new EmptyBorder(0, 0, 50, 0));
        panel.setBackground(Color.YELLOW);

        JTextField task = new JTextField();
        task.setText("xxxxxxxxxxxxxxxx");
        task.setMargin(new Insets(10, 10, 10, 10));
        // 告诉布局容器，需要对此组件进行加宽
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 6;
        gbc.weightx = 6;
        panel.add(task, gbc);

        JTextField remind = new JTextField();
        remind.setText("2021-07-24 20:30");
        remind.setMargin(new Insets(10, 10, 10, 10));
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 6;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        gbc.weightx = 1;
        panel.add(remind, gbc);
        panelList.add(panel);
        return panel;
    }

    /**
     * 动态添加任务输入框后，更新组件
     */
    private void updateUI() {
        // 最后一个不用动，所以size - 1
        for (int i = 0; i < panelList.size() - 1; i++) {
            jpl.add(Box.createVerticalStrut(10));
            panelList.get(i).setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.RED));
            jpl.add(panelList.get(i));
        }
        SwingUtilities.updateComponentTreeUI(frame);
        // 获得上下滚动条Bar对象，然后将滚动条的当前滚动值，设置为滚动条的最高值。完成自动滚动
        JScrollBar vsb = jsp.getVerticalScrollBar();
        vsb.setValue(vsb.getMaximum());
        jpl.revalidate();
    }

    // TODO 窗口尺寸变动后，更新组件大小

}
